from django.template import Library, Node
from django.db.models import get_model
from django.template import TemplateSyntaxError
register = Library()
      
class menu(Node):
     def __init__(self, model):
          self.model = get_model(*model.split('.'))
     
     def render(self, context):
          context['menu'] = render_menu(self.model)
          return ''
 
def get_menu(parser, token):
     bits = token.contents.split()
     if len(bits) != 2:
          raise TemplateSyntaxError, "get_menu necesita un argumento"
 
     return menu(bits[1])
     
get_menu = register.tag(get_menu)

def render_menu(obj):
     ret=[]
      
     for c in obj._default_manager.filter(padre__isnull=True).order_by('orden') :
          menu = {}
          menu['nombre'] = c.nombre
          menu['uri'] = c.uri
          menu['subm'] = obj._default_manager.filter(padre=c).order_by('orden')
          ret.append(menu) 
            
     return ret

from random import randint

@register.assignment_tag()
def random_number(length=4):
     return randint(10**(length-1), (10**(length)-1))